Refresher: Lists and Hashes
February 7, 2000
Technically, you should already know the basics behind these
two Perl data structures, as covered in
The Perl You Need to Know Part 1.
Let's review, as they say:
A list, also known as an array in many other
programming languages, is an ordered sequence of data items.
Perl lists are denoted with the @ character prefix,
and are defined thusly:
@colors=("red","green","blue");
Simple enough, we now have a list named colors which
contains three items, sometimes known as
elements, each a string value. Because a list is
ordered, the sequence of the items matters: the first item is
"red", the second is "green", and so on.
Although colors itself is a list, any single item in
the list is a Perl scalar value, which we can pluck
out as follows:
$firstItem=$colors[0];
Notice that we precede colors with the scalar prefix,
$, since we are accessing only one item in the list, not the
whole list itself. The subscript 0 refers to the first item
in the list, since list indices began counting at
zero, which was "red". Very elementary stuff,
indeed!
You can add an item to a list either using a direct
assignment to an unused index number, or, simply
"push" an item onto the end of the list using
the push function:
$colors[3]="magenta";
push(@colors,"magenta");
A hash takes the list concept and, though it pains one to
say this, "kicks it up a notch" (so says a certain
TV chef). The hash, more obtusely known as an associative
array, lets you associate two pieces of data with each
other, rather than a simple linear list of items. Hash items
are known as "key-value pairs", because
each hash item consists of a key (one piece of data)
which is associated with a value (another type of data). For
example, you can imagine such a pair where the key is
"color" and "blue" is the value. Hashes
are represented using the % prefix, such as:
%item=("color"=>"blue");
The above creates a hash named item with a key-value
pair of color->blue. As with lists, you access a single
hash value as a scalar, using the key value as the subscript
in your reference:
$itemColor=$item{"color"};
In this assignment, the variable $itemColor would
receive the value "blue". You can add any number
of additional keys to this hash -- unlike a list, however,
the order of the keys is irrelevent.
$item{"size"}="large";
$item{"price"}="22.99";
You can retrieve a list of all the keys held in a hash using
the keys function:
@itemKeys=keys (%item);
Above, the list @itemKeys would contain the items
"color", "size", and "price" ...
though not necessarily in that order. In fact, you don't know
what order they will be in, unless you have explicitly
sorted the keys which we'll look at shortly.
Now that we're comfortable with the concepts of lists and
hashes, it's time for some juggling!
The Perl You Need to Know Part 10: Untangling Lists and Hashes
The Perl You Need to Know
All Sorts of Sorts: Lists
|