Perl Hashes - Creating A Hash
(Page 2 of 5 )
If you are familiar with other programming languages, then you will know that a hash is similar to an associative array. Before we create our first hash, there are a few rules you must learn. The first one is the naming convention. Hashes are named like other lists, except that they start with a percent sign (%) rather than the ampersand (@). When you refer to a key you use the curly braces {}, as opposed to parentheses as in regular lists. When you create the hashes, you use parentheses. Okay, enough blabbering; let's create our first hash:
#!/usr/bin/perl
%Brownies = (1,'Chocolate', 2,'Fudge',3,'Vanilla',4,'Peanut Butter');
In the above example we created four key-value pairs. If we printed out the hash, this is how we would do so, and also, the result:
#!/usr/bin/perl
%Brownies = (1,'Chocolate', 2,'Fudge',3,'Vanilla',4,'Peanut Butter');
print %Brownies;
Which prints:
4Peanut Butter1Chocolate3Vanilla2Fudge
Not quite what we expected right? You will note that hashes are not ordered lists and will not necessarily print in the order you enter them. Also, you will notice that the key gets printed along with the value when we print in this manner. We will learn in a short bit how to print only the values when we want to print the entire hash.
Next: Printing from a Hash >>
More Perl Articles
More By James Payne