1. Home
  2. Computing & Technology
  3. Perl

Beginning Perl Tutorial - Data Types: Hashes

Readable Hash Initialization

By Kirk Brown, About.com

Next: Playing With Hashes

Like every other aspect of the Perl language, there are many ways to do things. In the previous examples, when we initialized a hash, we wrote it in the same way as a plain list.

@sampleList = ('Larry', 'Curly', 'Moe');
%sampleHash = ('name', 'Bob', 'phone', '111-111-1111');
While this is a perfectly legitimate way of assigning the data, it's a little difficult to read when you're glancing over the source code. The only difference, in fact, is the prefix character on the variable name - @ for a list, % for a hash. In order to keep from confusing or cluttering up the source code, lets use a clearer method of initializing a hash.
@sampleList = ('Larry', 'Curly', 'Moe');
%sampleHash = ('name' => 'Bob', 'phone' => '111-111-1111');
Using the => symbol between each key / value pair not only makes it more obvious that the data is a hash, but also clearly defines the relationship between each key and it's corresponding value. Since Perl ignores whitespace, you can make longer lists even more readable by spanning multiple lines.
%sampleBigHash = (
'name' => 'Bob',
'phone' => '111-111-1111',
'address' => '123 Fake St.',
'city' => 'Austin',
'state' => 'TX'
);
Next: Playing With Hashes

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.