Perl Programming Page 4 - Perl Hashes |
As we saw earlier, you cannot simply print all the values in a hash using the print command. You could, but then you would also get the keys associated with those values as well, which you may not want. Perl has a handy function, called “values,” that can help you achieve this goal: #!/usr/bin/perl %HowItIs = (Dumb,'You ', Fat,'YoMama ',UglyGenius,'James Payne ',Nerd,'James Payne '); print values(%HowItIs); This prints out just the values in the hash: James Payne James Payne YoMama You If we wanted to print out all the keys, and not the values, we can do that also, using another function, “keys”. Here it is in code: #!/usr/bin/perl %HowItIs = (Dumb,'You ', Fat,'YoMama ',UglyGenius,'James Payne ',Nerd,'James Payne'); print sort(keys(%HowItIs)); Note that I sorted this print out also: DumbFatNerdUglyGenius And of course if we wanted a list of both keys and values in a sentence, we can do that as well with the following nifty little program: #!/usr/bin/perl %HowItIs = (Dumb,'You ', Fat,'YoMama ',UglyGenius,'James Payne ',Nerd,'James Payne'); @All = keys(%HowItIs); foreach $ItIs(@All) {print "The key for $HowItIs{$ItIs} is $ItIsn"}; Which gives us the following result: The key for James Payne is Nerd The key for James Payne is UglyGenius The key for Yomama is Fat The Key for You is Dumb
blog comments powered by Disqus |
|
|
|
|
|
|
|