Lists and Hashes

Previous Table of Contents Next

Lists and Hashes

When I discussed how to initialize a hash, I hinted that hashes and arrays are somehow related. Whenever a hash is used in a list context, Perl unwinds the hash back into a flat list of keys and values. This list can be assigned to arrays, like any other list:

%Movies = ( 'The Shining' => 'Kubrick', 'Ten Commandments' => 'DeMille', Goonies => 'Spielberg'); @Data = %Movies;

At this point, @Data is an array containing six elements. (The even elementszero includedare directors' names, and the odd elements are movie titles.) You can perform any normal array operation on @Data, and then you can reassign the array to %Movies, as shown here:

%Movies = @Data;

By the Way

Perl stores hash keys in a seemingly random order, useful only to Perl. Perl makes no effort to remember the order in which the keys were placed into the hash, and it doesn't put them into any particular sequence when retrieving the keys. Getting them in order for display requires that you sort them (see the "Useful Things to Do with a Hash" section, later in this hour) or somehow remember the order they were inserted in (see the "Q&A" section at the end of this hour).

Arrays and hashes are similar in other respects. To copy a hash, you can simply assign the hash to another hash, like this:

%New_Hash = %Old_Hash;

When you put %Old_Hash on the right side of a hash initialization, where Perl would normally expect a list or array, Perl unwinds the hash into a list. This list is then used to initialize %New_Hash. In the same way, you can combine and manipulate hashes in ways similar to lists, as you can see here:

%Both = (%First, %Second);

%Additional = (%Both, key1 => 'value1', key2 => 'value2');

The first line combines two hashes, %First and %Second, into a third hash, %Both. Something to remember about this example is that if %First has keys that also appear in %Second, the second occurrence of the key-value pair replaces the first in %Both. In the second example, %Both is represented as a list of key-value pairs in the parentheses. Two additional key-value pairs are also in the parentheses. The entire list is then used to initialize %Additional.

    Previous Table of Contents Next
    © 2000- NIV