Perl Programming Perl: Another Round with Hashes |
In our previous issue we learned the basics of hashes -- such as how to create them, print individual values from them and print only the value. We also learned a way to print the keys. Additionally, we worked with some alternative methods to create hashes and assign values to them, such as using the => operator and using other hashes as their foundation. While we were at it, we learned to create variables and lists out of the elements within a hash. Want Some Hash with that Shake? Adding a value to a hash that already exists is similar to adding a value to a previously created list. In the following example, we begin by creating a hash name %Wrestler that will hold two key-value pairs, representing the Champ, CM Punk, and the Chump, Chavo Guerrero. We will then add a third value, 'The Miz', with the key, Dumb. Here it is in code: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero '); print values(%Wrestlers); print "\n\n"; $Wrestlers{Dumb}=' The Miz '; print values(%Wrestlers); When we run this program, we get the following result: CM Punk Chavo Guerrero CM Punk The Miz Chavo Guerrero Since we are only adding one value and key, we used the $Wrestlers variable and enclosed our key in curly braces {Dumb}. We then told the program to assign the value 'The Miz' to the key and assigned the $Wrestlers variable to our hash. Note that the name $Wrestlers matches the name of the hash, %Wrestlers. If they differ, this program will not work as we intended. We can also add a value to a hash by using a variable. Let's say we have a variable that holds the name of a wrestler. Here is how we add him to the %Wrestler hash: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero '); $New="Big John Stud"; print values(%Wrestlers); print "\n\n"; $Wrestlers{OldSkool}=$New; print values(%Wrestlers); Note that we had to assign a key for our variable (OldSkool). Without this, the code would not have worked properly, as Perl would not have known how to reference Big John Stud. This program gives us the result: CM Punk Chavo Guerrero Big John Stud CM Punk Chavo Guerrero If you want to see how the keys to verify that the new additions were stored properly, you can do so like this: #!/usr/bin/perl %Wrestlers=(Champ, ' CM Punk ', Chump, ' Chavo Guerrero '); $New="Big John Stud"; print values(%Wrestlers); print "\n\n"; $Wrestlers{OldSkool}=$New; @All = keys(%Wrestlers); foreach $Stuff(@All) {print "The key for $Wrestlers{$Stuff} is $Stuffn"}; Giving us the result: The key for Big John Stud is OldSkool The key for CM Punk is Champ The key for Chavo Guerrero is Chump
blog comments powered by Disqus |
|
|
|
|
|
|
|