1. Home
  2. Computing & Technology
  3. Perl

Beginning Perl Tutorial - Data Types: Hashes

What is a Hash?

From About.com

Next: Accessing Hash Elements

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:

%myHash
%special_events
%disk45
A 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.
%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/perl
%contactInfo = ('name', 'Bob', 'phone', '111-111-1111');
print %contactInfo;
This will output:
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

Explore Perl

More from About.com

  1. Home
  2. Computing & Technology
  3. Perl
  4. Perl Tutorials
  5. Beginning Perl Tutorial - Data Types: Hashes

©2008 About.com, a part of The New York Times Company.

All rights reserved.