Chapter 16. Some Advanced Perl Techniques
What we’ve put in this book so far is the core of Perl, the part that every Perl user should understand. A few other techniques, while not obligatory, are still valuable tools to have in your toolbox. We’ve gathered the most important of those in this chapter.
Don’t be misled by the title of the chapter; these techniques aren’t more difficult to understand than the rest of the book. They are only “advanced” in the sense that they aren’t necessary for beginners. The first time you read this book, you may want to skip (or skim) this chapter so you can get right to using Perl. Come back to it later when you’re ready to get more out of Perl. Consider this entire chapter a huge footnote.[349]
Trapping Errors with eval
Sometimes, your ordinary, everyday code can cause a fatal error in your program. Each of these typical statements could crash a program:
$barney = $fred / $dino; # divide-by-zero error? print "match\n" if /^($wilma)/; # illegal regular expression error? open CAVEMAN, $fred # user-generated error from die? or die "Can't open file '$fred' for input: $!";
You could go to some trouble to catch some of these, but it’s hard to get them all. (How could you check the string $wilma
from that example to ensure it makes a valid regular expression?) Fortunately, Perl provides a way to catch fatal errors: wrap the code in an eval
block:
eval { $barney = $fred / $dino } ;
Even if $dino
is zero, that line won’t crash the program. The eval
is an expression ...
Get Learning Perl, Fourth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.