Lesson 4 – Hashes and Arrays

I've got sunshine on a cloudy day.
When it's cold outside, I've got the month of May.
I guess you'll say, what can make me feel this way?
My perl, talkin' 'bout my perl

We've already talked a little bit about arrays.  Arrays are lists of data.  Arrays are always indexed by an integer.  If you want to index the data in your list by something other than an integer, then you'd have to use an "associative array," commonly referred to as a "hash" or "hash table."  Here's an example:

$days{"Sunday"} = 0;
$days[0] = "Sunday";

$days{"Monday"} = 1;
$days[1] = "Monday";

$days{"Tuesday"} = 2;
$days[2] = "Tuesday";

$days{"Wednesday"} = 3;
$days[3] = "Wednesday";

$days{"Thursday"} = 4;
$days[4] = "Thursday";

$days{"Friday"} = 5;
$days[5] = "Friday";

$days{"Saturday"} = 6;
$days[6] = "Saturday";

print keys %days, "\n";
print join(" ", keys %days), "\n";
print join(" ", values %days), "\n";
print join(" ", @days), "\n";
Run the program and see what you get.  Notice that the first time we tried to print the keys, they all got concatenated together with no spaces in between.  The second print statement fixes that problem.

Also notice that in the above example, we have an array, @days, and we have a hash, %days.  Elements in arrays are referenced by the notation $array[index], where index is an integer.  For hash tables, the syntax is a little bit differenent:  $hash{key}, where key is a string value.

We can rewrite the program in a little bit better way, like so:
@days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
%days = ( "Sunday" => 0, "Monday" => 1, "Tuesday" => 2, "Wednesday" => 3,
    "Thursday" => 4, "Friday" => 5, "Saturday" => 6 );
@keys = keys %days;
@values = values %days;
print "hash keys: @keys\n";
print "hash values: @values\n";
print "array values: @days\n";

OK, here's your first homework assignment:

Homework 1

Write a perl script that reads in a line of text (see previous lessons for examples of how to do this).  Check to see if the line of text is a number (you can use regular expressions, or some other clever way to do this.  Be creative.  Read the manual if necessary.)  If it's a number, then print out the day of the week that it represents, using the hash tables above.  If the line of text is not a number, then assume that it is a day of the week and look it up in the %days hash, and print out the number for that day.

Send me a copy of the program when you are done:  flong@skcc.org.  Good luck!