Lecture#8 Outline


Chapter 5 - Hashes

A hash is a data structure like an array, but instead of using numbers as the indexes, you can use strings, and these strings are called keys. You use a hash when you need to 'relate' the keys to the data, for example people's names to their addresses, social security number to name. Keys must be unique. Like arrays, the values don't have to be the same type. Hashes aren't interpolated, but hash elements are.

Accessing Hash Elements
$hashname{$key}

$person{"999-11-1234"} -> would give the name of the person with SS# 999-11-1234

The key can be an expression or variable if you wish: $first3="999"; print $person{$first3."-11-1234"};

Reassigning an element replaces it...using a key that doesn't exist creates it:
$person{"999-22-2222"}= "Alan"; #Creates the element if necessary

Accessing a non-existant element returns undef

The Whole Hash
The whole hash is represented by putting a % before the hash name: %person is all of the key, value pairs in the hash.

Here's some examples of what you can do with the whole hash:

%newhash = %person; #copy it into a new hash
@keyvaluepairs = %person; #The array now has the 1st key as the 1st element, the 1st value as the 2nd, etc...
%iphash = reverse %hostnames; #Now we can do reverse DNS lookups!

Big Arrow
Instead of having to assign a hash like this (which works fine):
%myhash = ("one", 1, "joe", "gene", "key1", "value1");

Perl provides the following that makes it easier to read:

%myhash = (
    "one" => 1,
    "joe" => "gene",
    "key1" => "value1"
);

5 Hash Functions
The keys function
@thekeys = keys %myhash;
print "@thekeys"; #Prints one joe key1
$count = keys %myhash; #scalar context, $count gets 3

The values function
@thevals = values %myhash;
print "@thevals"; #Prints 1 gene value1

The each function
($key, $value) = each %myhash;

Each returns a key, value pair. Useful for iteration:
while (($key, $value) = each %myhash)
{
    #Code
}

The exists function
if (exists $myhash{"two"}) {
    #This is executed if an entry has the key "two"
}

The delete function
delete $myhash{"one"}; #if it exists, it deletes it, otherwise does nothing


CSC255 - Alan Watkins - North Carolina State University