Computer Sciences Department logo

CS 368-3 (2012 Summer) — Day 5 Homework

Due Thursday, July 5, 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 class of units, such as length or mass or volume. Note: Your script must convert among at least four different units (e.g., meters, kilometers, feet, 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

You must 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


Here are some specific tests to consider:

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 conversion factors…


Do the work yourself, consulting reasonable reference materials as needed. Any resource that provides a complete solution or offers significant material assistance toward a solution not OK to use. Asking the instructor for help is OK, asking other students for help is not. All standard UW policies concerning student conduct (esp. UWS 14) and information technology apply to this course and assignment.

Hand In

A printout of your code, ideally on a single sheet of paper. Be sure to put your own name in the initial comment block. Identifying your work is important, or you may not receive appropriate credit.