Lab 3 - Lists and Hashes

Overview

Last week's lab introduced you to variables - named locations in which we can store values. We learned about the most basic type of variable in Perl, the scalar, and that the name of a scalar always starts with $.

In class, you learned about two more types of variable:

  • the list (a collection of scalars, name starts with @)

  • the hash, or associative array (represents relationships between scalars, name starts with %).

This lab will give us some practice with all these concepts.

 

Intro: the foreach loop
One more thing to know before you get started is how to use a foreach loop. A foreach loop lets you repeat an action for each element of a list of elements. You might use it like this:

#!/usr/bin/perl -w
use strict;

my @names = qw( Alice Bob Cindy );

foreach my $name (@names) {
   print "One of the names is $name\n";
}
jpr@sulu (i211/lab3) $ ./printnames.pl
One of the names is Alice
One of the names is Bob
One of the names is Cindy

We will use foreach loops often when we deal with list-like data, like arrays and hashes.

 

Intro: Changing a scalar to a list with split

A simple way to change a scalar into a list is with the split function. We'll use split often, to deal with a string one piece at a time.

#!/usr/bin/perl -w
use strict;

my $food = "apple banana orange strawberry";
my @items = split / /, $food;

foreach my $item (@items) {
   print "One of the items is $item.\n";
}
jpr@sulu (i211/lab3) $ ./printfruits.pl
One of the items is apple.
One of the items is banana.
One of the items is orange.
One of the items is strawberry.

Now that we have those two tools, we can get started with this lab!

 

Exercise 1: Using Lists
Your first exercise is to write a simple program that should give you some practice in creating and manipulating lists.

Do this:
Create a program called double_list.pl that does the following:
  1. Prompt the user for a list of numbers as a string. Numbers should be separated by whitespace.
  2. Use split to split the string into a real list.
  3. Use a foreach loop to double each number in the list.
  4. Print the list back out, with numbers separated by spaces again
Some sample output is shown below.
jpr@sulu (i211/lab3) $ ./double_list.pl
Enter some numbers => 1 2 3 4 5 12
Here are your numbers, doubled : 2 4 6 8 10 24
jpr@sulu (i211/lab3) $

 

Exercise 2: Using Hashes

This exercise should give you some practice using hashes, an immensely useful data type that tracks associations between variables. Other languages call hashes "associative arrays" or "associative lists" or "alists", so you'll sometimes see these used in Perl as well.

An important thing about hashes is that the keys in hashes are unique - each key may only appear once. This can come in handy in a lot of different situations, including this one.

Do this:

Write a program called unique.pl that accepts a list of space-separated words and prints out only the unique ones - that is, no word should appear twice in the output.

Hints:

  • Use split to cut the string into a list of individual words.
  • Use a foreach loop to move over the list, and put each element of the list in a hash. Remember that putting the same thing in a hash twice doesn't change the hash, since hash keys are unique.
  • Use the keys function to retrieve the keys of the hash. Do they satisfy the requirements?
Some sample output is shown below.
jpr@sulu (i211/lab3) $ ./unique.pl
Enter some words => apple apple banana orange banana qwerty smooth qwerty
Unique words are banana qwerty apple smooth orange
jpr@sulu (i211/lab3) $ ./unique.pl
Enter some words => apple apple apple apple
Unique words are apple
jpr@sulu (i211/lab3) $

 

Making change
Time to tie everything together. Let's write a program that performs a semi-useful function - counting change.

jpr@sulu (i211/lab3) $ ./makechange.pl
Give me a list of coins => quarter dime quarter nickel penny penny
You have 0 dollar(s) and 67 cent(s).
jpr@sulu (i211/lab3) $ ./makechange.pl
Give me a list of coins => quarter quarter dime quarter dime quarter penny
You have 1 dollar(s) and 21 cent(s).
jpr@sulu (i211/lab3) $

Here are some hints:
  1. Use split to break the string of coins into a list of individual coins, as usual.
  2. Use a hash to track the value of each coin. Initialize your hash in your code. The first line if the initialization might look like this:
    my %coin_values = ( 'quarter' => 0.25,
        # ... more stuff here ...
        );
  3. Don't worry about illegal coin names, or about coin names not in lowercase.
  4. Use a foreach loop to go over the list of coins you built up earlier, and add their values to another variable.
Do this:
Write makechange.pl. First try to create a version that just prints out the number of cents the person has (e.g. "You have 121 cents"). Once you have that version done, figure out how to separate the dollar amount from the penny amount (e.g. "You have 1 dollar(s) and 21 cent(s)").

 

Turn in your assignment
As usual, let's make a tarball of your assignment files (make sure they are ALL in the lab3 directory!) For this lab, you should have the following files:
  • double_list.pl
  • unique.pl
  • makechange.pl
As a reminder, here's the command you can use:

jpr@sulu (i211/lab3) $ cd ..
jpr@sulu (i211) $ tar czv lab3 > lab3.tar.gz
double_list.pl
unique.pl
makechange.pl
jpr@sulu (i211) $

You should then download this lab2.tar.gz file and upload to the Lab 2 assignment on Oncourse. Make sure you press "submit" and "finish" enough times to actually upload your file.

Okay, that's it! Have a good weekend.

Coin image from http://www.coins-for-magic.de/coins-for-magic.jpg
Thanks to Jacob Ratkiewicz for lab content, Sid Stamm for CSS stylesheets, and Rob Signorelli for original syntax-highlighting JavaScript.