Computer Sciences Department logo

CS 368-1 (2011 Summer) — Day 5 Homework

Due Tuesday, July 19, at the start of class.


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


The main point of this exercise is, of course, to use subroutines. But we want to write a useful script, too, so let’s write a basic unit-conversion calculator. Your script should convert among 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.

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

Write the following three subroutines (at least):

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”), documented here.

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

Extra Challenge

Can you avoid defining the conversion factor between every pair of units? Imagine you have 10 different length units (inch, foot, mile, meter, etc.); there are 10 × 9 = 90 unique conversion pairs (e.g., inch → foot). But I claim you need only 10…


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 code on a single sheet of paper. Be sure to put your own name in the initial comment block of the code. Identifying your work is important, or you may not receive appropriate credit.