Appendix A. Exercise Answers

This appendix contains the answers to the exercises that appear throughout the book.

Answers to Chapter 2 Exercises

  1. Here’s one way to do it:

    #!/usr/bin/perl -w
    $pi = 3.141592654;
    $circ = 2 * $pi * 12.5;
    print "The circumference of a circle of radius 12.5 is $circ.\n";

    As you see, we started this program with a typical #! line; your path to Perl may vary. We also turned on warnings.

    The first real line of code sets the value of $pi to our value of π. There are several reasons a good programmer will prefer to use a constant[30] value like this: it takes time to type 3.141592654 into your program if you ever need it more than once. It may be a mathematical bug if you accidentally used 3.141592654 in one place and 3.14159 in another. There’s only one line to check on to make sure you didn’t accidentally type 3.141952654 and send your space probe to the wrong planet. It’s easier to type $pi than π, especially if you don’t have Unicode. And it will be easy to maintain the program in case the value of π ever changes.[31] Next we calculate the circumference, storing it into $circ, and we print it out in a nice message. The message ends with a newline character because every line of a good program’s output should end with a newline. Without it, you might end up with output looking something like this, depending upon your shell’s prompt:

    The circumference of a circle of radius 12.5 is
    78.53981635.bash-2.01$[]

    The box represents the input cursor, blinking at the end of ...

Get Learning Perl, 5th 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.