The scalar is the building block of all perl data types. A list is just an ordered group of scalars indexed by number. A hash is also a group of scalars, but rather than being ordered by number, it is an unordered list that is indexed by yet another set of scalars called keys. This may seem a bit confusing at first - lets go back to our empty box metaphor. A hash is simply a scattered group of these boxes. Rather than being in a nice, neat line, they're kept in no particular order but the boxes are identified with a special label (a key) on the outside.
The symbol for a hash is the % sign, and the naming conventions remain the same - any combination of letters, numbers and the underscore character, but you may not begin it with a number:
%myHashA hash is also called an associative array, or an array where each value is associated with a corresponding key. Just like a list, you initialize a hash with a set of values inside parentheses. Rather than pushing each element into the list in order, Perl will alternate - setting the first element as a key, and the next as that keys' value, and so on.
%special_events
%disk45
%contactInfo = ('name', 'Bob', 'phone', '111-111-1111');Just like lists, a hash will output everything if you print it as a single item.
#!/usr/local/bin/perlThis will output:
%contactInfo = ('name', 'Bob', 'phone', '111-111-1111');
print %contactInfo;
nameBobphone111-111-1111$Since both the keys and the values are simple scalars, the same rules apply - they can be any type of data from integers to strings to more scalars.
Next: Accessing Hash Elements
