Appendix A. Exercise Answers

This appendix gives the answers for the exercises found at the end of each chapter.

  1. Here’s one way to do it:

    $pi = 3.141592654;
    $result = 2 * $pi * 12.5;
    print "radius 12.5 is circumference $result\n";

    First, we give a constant value (π) to the scalar variable $pi. Next, we compute the circumference using this value of $pi in an expression. Finally, we print the result using a string containing a reference to the result.

  2. Here’s one way to do it:

    print "What is the radius: ";
    chomp($radius = <STDIN>)
    $pi = 3.141592654;
    $result = 2 * $pi * $radius;
    print "radius $radius is circumference $result\n";

    This is similar to the previous exercise, but in this case, we’ve asked the person running the program for a value, using a print statement for a prompt, and then the <STDIN> operator to read a line from the terminal.

    If we had left off the chomp, we’d get a newline in the middle of the displayed string at the end. You must get that newline off the string as soon as you can.

  3. Here’s one way to do it:

    print "First number: "; chomp($a = <STDIN>);
    print "Second number: "; chomp($b = <STDIN>);
    $c = $a * $b; print "Answer is $c\n";

    The first line does three things: prompts you with a message, reads a line from standard input, and then gets rid of the inevitable newline at the end of the string. Note that because we are using the value of $a strictly as a number, we can omit the chomp here, because 45\n is 45 when used numerically. However, such careless programming ...

Get Learning Perl on Win32 Systems 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.