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 Done!
You must write the following three subroutines (at least):
get_valid_unit(): Asks the user for a unit label (e.g., 'm' for meter, or 'ft' for feet) and accepts input. Checks the input against the valid unit labels. If the label is OK, returns the label; otherwise, prints a message and asks for the unit label again.
get_valid_number(): Asks the user for a number and accepts input. Checks to make sure the input is an integer (see below for hints). If the number is OK, returns it; otherwise, prints a message and asks for a number again.
convert(number, from_unit, to_unit): Convert a number from one unit to another; returns the resulting number.
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:
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.
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.