CS 368 (Summer 2009) — Day 5 Homework

Due Tuesday, July 21st, at the start of class.

Description

Write a Perl script to do unit conversions, focusing on the DRY principle and, thus, subroutines.

Details

The main point of this exercise is, of course, to use subroutines. But we want to write a useful script, too, so let’s do a basic unit-conversion calculator. For simplicity (if you want), you may stick to a single type of units, such as length or mass or volume. Note: Your script must convert among at least three different units (e.g., meters, feet, and miles)! More is OK.

Here is one possible interaction style.

```% homework-05-script
Convert from units: ft
Convert to units: m
Length in ft to convert: 42

42 ft = 12.8016 m

Convert from units: lb
Sorry, I don't know anything about 'lb' units!

Convert from units: q
Done!

%```

Write at least the following subroutines:

• Get and validate a unit label (e.g., 'm' or 'ft')
• Get and validate a number (integer only is fine)
• Convert a number from one unit to another

For input validation of numbers, it is sufficient to make sure each character is a digit. If you already know regular expressions, knock yourself out. Otherwise, you can step through each character in the input string and see if the character is greater than or equal to the string '0' AND less than or equal to the string '9'. There are two bits of Perl that you may not know yet.

To get the length of a string, use the length function:

`my \$string_length = length(\$string);`

To get the character at a certain position within a string, use the substr function (short for “substring”):

`my \$character = substr(\$string, 4, 1); # fifth character of \$string`

Important question to consider upfront: How will you represent the constant conversion factors in your script such that they follow the DRY Principle?

Reminders

Do the work yourself, consulting reasonable reference materials as needed; any reference material that gives you a complete or nearly complete solution to this problem or a similar one is not OK to use. Asking the instructors for help is OK, asking other students for help is not.

Hand In

A printout of your script on a single sheet of paper. At the top of the printout, please include “CS 368 Summer 2009”, your name, and “Homework 02, July 16, 2009”. Identifying your work is important, or you may not receive appropriate credit.