|
Date Published: 1999-09-01
by D. Jasmine Merced
TNS, Inc.
Arrays
Also known simply as "lists", arrays store multiple pieces of data. Array definitions are preceded by
a @. Each piece of data in an array is called an element. Example:
@months = ("January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", "November", "December");
If the elements are all one alphanumeric word, this could also be written as:
@months = qw(January February March April May June July August September
October November December);
The qw tells perl that each element of the array is separated by a space
(called in perl lingo a "whitespace").
If the elements are 2 or more words, each element must be enclosed in single or double quotes, following
the same guidelines as variables (above).
Accessing Elements in an Array |
|
You may be wondering how perl gets a specific element from an array.
Array elements are accessed by their numeric placement in the list, starting with 0 (zero). In
the above example, January is 0, February is 1, March is 2, all the way to December, which is 11.
Technically, individual array elements "breaks down" to one or more scalars and can be used by the programmer the
same way scalars are used. For example, if you wanted to get August, the way to access it from the array
is $months[7] - which tells perl to grab the 8th element from the
@months array (Remember, 0, not 1 is the first element). From this point,
$months[7] can be treated like any other scalar.
Hashes store multiple pieces of data. While the array definition begins with a @, individual elements are accessed by their numeric placement in the array.
Next month, we're going to discuss hashes (associative arrays)... Stay tuned...
D. Jasmine Merced is a partner in Tintagel
Net Solutions Group, Inc. and the administrator of The Perl Archive. She also serves as a Director of
the World Organization of Webmasters.
|