O'Reilly logo

Learning Perl, Fourth Edition by brian d foy, Tom Phoenix, Randal L. Schwartz

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required