Can I store more than one thing in a hash—for instance, if I need to store several things (a list) by one key?
Yes. Two basic methods are involved. The first (and most cumbersome) is to format the value portion of the hash element into something recognizable, such as a comma-separated list. Whenever you store the hash element, you assemble the list into a scalar by using join, and whenever you retrieve a value from a hash, you split the scalar back into a list by using split. This method is cumbersome and error-prone.
The other method is to use a reference. References allow you to create hashes of arrays, hashes of hashes, and other complex data types. Using references to create complex structures is easy when you get the hang of it. This topic will be covered in Hour 13, "References and Structures."
How can I keep my keys in the order in which I assigned them to the hash?
Again, you can keep them in order in a couple of ways. The first method, which isn't easy, is to keep track of the insertion order yourself. One technique is to use an array that mirrors the hash. As you put new elements into the hash, you use push to put the same key into an array. When you need to see the insertion order, simply use the array instead of the keys function. This method is complicated and likely to be buggy.
The far superior method is to use the module Tie::IxHash. This module causes the keys function to return the hash keys in insertion order, just as you wanted. You can find an explanation of how to use modules in Hour 14, "Using Modules."
Can you suggest a convenient way to write my hash into a file?
Yes. Modules such as Data::Dumper or Storable can reformat data types such as hashes and arrays into easily storable scalar values, which can be written to text files. These modules also have functions that take those formatted scalars and re-create the original structure you stored.
In Hour 15, "Finding Permanence," you'll see that an even easier way to write a hash into a file is to use DBM files. DBM files allow you to tie your hash to a disk file. When you alter the hash, the disk file changes. The disk file causes your hash to be preserved as long as the file is intact.
© 2000- NIV