Array Manipulation in Perl - Hash Bang (Page 3 of 9 )
Perl also allows you to replace indices with user-defined "keys", in order to create a slightly different type of array, called a "hash" or "associative array". Each key is unique, and corresponds to a single value within the array.
#!/usr/bin/perl
# define hash
%dinner = ("starter" => "fried squid rings", "main" => "roast chicken", "dessert" => "chocolate cake");
In this case, %dinner is an associative array variable containing key-value pairs. The % symbol before the variable name indicates that it is an associative array, while the => symbol is used to indicate the association between a key and its value.
Now, in order to access the value "fried squid rings", I would use the key "starter" and the notation $dinner{"starter"}, while the value "chocolate cake" would be accessible via $dinner{"dessert"}. Here's an example:
#!/usr/bin/perl
# define hash
%dinner = ("starter" => "fried squid rings", "main" => "roast chicken", "dessert" => "chocolate cake");
# prints "fried squid rings"
print $dinner{"starter"};
Note the use of curly braces here around the key name, and contrast it with the use of square braces for the index notation used in regular arrays.
As with arrays, you can also use this notation to define an associative array incrementally - this line of code
#!/usr/bin/perl
# define hash
%dinner = ("starter" => "fried squid rings", "main" => "roast chicken", "dessert" => "chocolate cake");
is equivalent to these:
#!/usr/bin/perl
# define hash
$dinner{"starter"} = "fried squid rings";
$dinner{"main"} = "roast chicken";
$dinner{"dessert"} = "chocolate cake";
Note that when using an associative array, Perl usually re-sorts the key-value pairs such that they are optimized for retrieval. Therefore, it's not a good idea to rely on your original element positions when accessing values in a hash; instead hash values should always be accessed by their respective keys.
Next: Harnessing Elements >>
More Perl Articles
More By Harish Kamath, (c) Melonfire