Workshop in Computational Bioskills - Lesson 3 - Hashes

Workshop in Computational Bioskills - Spring 2009

Lesson 3 - Perl II

Back to Lesson 2
Part 1 - Hash tables/Associative Arrays (%)
Part 2 - Control flow

Hashes (Associative Arrays):

a Hash or an Associative Array is a different kind of a list.

Here, a cell is labeled by any scalar, instead of the natural numbers in lists.
As always, the cell content can be any type of scalar.

$h{"sunday"} = "blue";
$h{"monday"} = "red";
$h{"tuesday"} = "black";
$h{"wednesday"}= "yellow";
$h{"thursday"} = "orange";
$h{"friday"} = "green";
$h{"saturday"} = "purple";

This can be written nicer in the following format:
%h = (
     sunday => blue,

     monday => red,
     tuesday => black,
     ...
     saturday => purple,
);

Keys can be just as well numbers:

$h{13.2} = 12.3;
$h{1e-5} = 42;
$h{0.00001} = 13;
# This will overide 42, since 1e-5 = 0.00001 !

Hash elements has no order:

Due to the revolutionary naming scheme, there is no inherent order on the hash elements.

Hash commands:

- keys
The "
keys(%h)" command returns a list (in some arbitrary order) of the cells' names in %h.

- values
Similarly, "
values(%h)" returns a list of the values stored in the hash %h.
Luckily enough, the two commands: keys() & values(), should work in the same order.

- each
There's another way of iterating a hash, though.
"
each(%h)" returns the next pair of (key, value).
while (($k, $v) = each (%h)) {
     print "$k --> $v\n";
}
This code will iterate ovel all elements in the hash %h, and print them.

- delete
So far, we've seen ways of adding elements to a hash. But how can we delete them ?
$k = "tuesday";
delete $h{$k}; # will delete the element named $k.

- exists
It is possible to check if a cell exists before reading from it.
(instead of getting an "undef" value)
delete $h{"friday"} if (exists $h{"friday"});

Slicing a hash:

Just like lists, hashes can be sliced.
@colors = @h{"sunday","monday","wednesday"};
@h{"sunday","monday","wednesday"} = ("red", "cyan", "magenta");

This summarizes Hashes. Now Let's continue to Lesson 3 - Perl II

[Based upon "Learning Perl, 2nd Ed.", by Randel L. Schwartz & Tom Christiansen, Chap. 5]