Perl Programming Page 2 - Perl: More on Data Types and Operators |
Writing, apparently, is hungry work. Or maybe I am just a greedy pig. For some reason, this next topic makes me think of food...hashes, hash browns...mmm, yummy. Anyway, as I was saying, the third data type is Hashes. Hashes are like lists, but they aren't in order. Instead, they are indexed by a second set of scalars called keys. This might not make sense yet, but bear with me; it will. Observe the following masterful code written by yours truly: #!/usr/local/bin/perl %fat_people = {'James ', '400 ', 'YoMama ', '900 '}; print %fat_people This will output: James 400 YoMama 900 Please note several things. Because we used print to print the whole hash, it printed every value. Second, you will notice that the naming convention for hashes is the same as other data types, with the exception that hashes begin with a % symbol. So this is where Hashes begin to make sense. Let's say that I want to print only YoMama's weight from that hash. I would do so in the following manner: #!/usr/local/bin/perl %fat_people = {'James ', '400 ', 'YoMama ', '900 '}; print $fat_people{'YoMama'}; This would result in the print out: 900 In the above code, the weight 900 is printed because we used the index key, YoMama. Instead of lining everything up in order, Hashes use the first scalar as an index key, and the second as the data, and so forth. If I wanted to print the weight of James (or 400) I would have called James instead. Simple? Again, you will note that when I printed out the single result, I changed to the $ symbol, because again, I am printing only scalars. To make it a smidge more clear, you could also write the above hash this way: %fat_people = ('James ' => '400', 'YoMama' => '900'
blog comments powered by Disqus |
|
|
|
|
|
|
|