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

No credit card required

A.1. Chapter 2

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: ";
\$pi = 3.141592654;
\$result = 2 * \$pi * \$radius;

This is similar to the previous exercise, but here 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. It's important to get that newline off the string as soon as we 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 since 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 would ...

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

No credit card required