eWebProgrammer eweb  

Advanced Perl  «Prev  Next»
Lesson 13 Aggregate data types
Objective Learn what the two basic aggregate data types are in Perl.
Sometimes it does not suffice to store a single dimension of data. Many times data come in groups, in pluralities, like raindrops beating on the tin roof of the carport while you're trying to sleep.
For these purposes, Perl has two basic aggregate data types:
  1. arrays and
  2. hashes.
The simpler form is the array. It's simply a two-dimensional scalar.
Indexed numerically, starting at zero, the contents of a Perl array is simply an ordered list of scalar variables.
The more complex form is the hash (also called associative array, but it is easier to say hash. A hash is like an array, but it's indexed with scalar values instead of numbers.
The next lesson will go into detail about working with arrays, and the lesson following that will explore hashes.
In Perl, an array is an ordered list of scalars. The following is how you might assign a few numbers to an array:
my @even = ( 2, 4, 6, 8, 10 );
For an array, the variable is preceded by an @ (at) sign, so the mnemonic for this is an “@array.” When you have a list of items, separate them with a comma and use parentheses () around them.
So, the preceding code has an array on the left and a list on the right, and you are assigning the list to the array. Of course, just as with scalars, you can use any kind of data you need to use. You can even assign lists with a mix of strings or other scalars to an array:
my $nine = 9;
my @stuff = ( 7, ‘of’, $nine );
If you just print the array as shown in the following example, what happens?
my $nine = 9;
my @stuff = ( 7, ‘of’, $nine );
print @stuff, “\n”;
print “@stuff\n”;
Although there are ways you can tweak this, the code just presented will probably print the following:
7 of 9