Computer Sciences Department logo

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

Due Tuesday, July 20th, 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 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


Write at least the following subroutines:

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?


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 output 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.