About dieing and exiting in Perl
Archive - Originally posted on "The Horse's Mouth" - 2008-11-01 06:36:04 - Graham EllisIf you want to end a program in Perl, you can get out quickly enough with an exit function call. But that's probably just a part of what you'll be wanting to do - you'll be wanting to generate an error message on the error channel (STDERR) too, and perhaps to tell your user rather more about why the program died.
The die function provides a message on STDERR and the exits your program. If you add a \n on as the last character, it will NOT tell you the line number in your code where it died, but with the \n it does tell you.
Note that if you have your die function tell you the line number, it will also tell you how many lines have been read from the latest file. At first, this will seem odd but it's very useful indeed in helping to identify which line of a long data file caused your program to halt!
Some useful variables to use within die strings:
%body% - program name
$. - number of lines of data read in
$! - error message from open function
If you're writing a Perl module, you'll also want to have a look at croak within the Carp module, as this reports information about where you were in the calling module rather than the actual line number of failure ... which when you think about it is exactly what the programmer who's making use of you module wants to know.
Some sample code:
@ARGV < 2 and die ("Usage: %body% perlregex filename\n");
($lookfor, $file) = @ARGV;
open (FH,$file) or die ("%body%: Input file $file problem\n$!");
while (<FH>) {
if (/$lookfor/)
{die("Data trap");}
}
print "Completed Correctly\n";
And some sample output from it:
Dorothy:p82 grahamellis$ perl chink
Usage: chink perlregex filename
Dorothy:p82 grahamellis$ perl chink Java ../requst.xyz
chink: Input file ../requst.xyz problem
No such file or directory at chink line 33.
Dorothy:p82 grahamellis$ perl chink Java ../requests.xyz
Data trap at chink line 35, <FH> line 2.
Dorothy:p82 grahamellis$ perl chink Javascript ../requests.xyz
Completed Correctly
I have indexed a copy of this code for your use under our Perl Standards module. In Perl, there are lots of different ways to do almost anything - and it's vital to come up with a concensus approach that's best for your organisation rather than using a bit of everything ... so I'll talk about Perl coding standards - how to write maintainable Perl - on every course I give from learning to program in Perl right through to Perl for larger projects
You can see the first few lines of each data file that we use in our examples in our Data directory. For copyright reasons, a few of the data files we use on our courses cannot be publicly downloaded; if you are a past delegate who would like a complete copy of any of the data files rather than just a sample of a few lines, please let me know.