Cover V05, I12
Article
Listing 1
Listing 2
Listing 3
Listing 4
Listing 5
Sidebar 1

dec96.tar


Sidebar: Arrays in Perl

Perl has two kinds of arrays: regular and associative. Regular arrays have integer subscripts, and individual elements are referenced as $array[1]. The whole regular array can be referenced in an array context as @array.

Associative arrays have strings for subscripts, and individual elements are referenced as $assoc{"key"} (notice the different brackets). The whole associative array can be referenced in an array context as %array. Both kinds of arrays are used in syslogconf.

To illustrate usage of both array types, start perl interactively and type the following:

@twee = ('tweedle-dee', 'tweedle-dum');
print ("twee[0] = $twee[0], twee[1] = $twee[1]\n");
print ("$twee[0] $twee[1]\n");
print ("@twee\n");

Terminate input with Control-D and you will see the following:

twee[0] = tweedle-dee, twee[1] = tweedle-dum
tweedle-dee tweedle-dum
tweedle-dee tweedle-dum

Notice in particular that the second and third lines produce identical output; that is, printing @array is shorthand for printing each entry of the array separated by spaces.

Next, start perl interactively again and type:

%twee = ('t1', 'tweedle-dee', 't2', 'tweedle-dum');
print ("twee{'t1'} = $twee{'t1'}, " .
"twee{'t2'} = $twee{'t2'}\n");
print ("$twee{'t1'} $twee{'t2'}\n");
print ("%twee\n");

You will see the following:

twee{'t1'} = tweedle-dee, twee{'t2'} = tweedle-dum
tweedle-dee tweedle-dum
%twee

Note that %twee in the third print statement doesn't produce the same result as @twee did above. In other words, %twee is not an alias for the whole associative array in a print statement.

Regular arrays are used in Perl for much the same tasks as in other programming languages - to contain related sets of values in an easily accessible fashion. Associative arrays are useful when the relationship between key and value, not just the value itself, is important. They can help with procedures such as keeping track of input with arbitrary values. In particular, if you know that the key for certain input will always be in the same field, you can simply use that field as a key for an associative array without having to code for all possible input values in that field.

In syslogconf, a natural use of associative arrays is to use all of the possible priorities by name as keys. This is much easier to read, program, and maintain than a multidimensional regular array using the subscripts of the facility and level arrays as indices.