Perl Programming Page 4 - Perl: Another Round with Hashes |
We don't have to simply do away with our deleted value. In the following code, we will store it in a variable and append it to a sentence: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); print values(%Wrestlers); print "\n\n"; $Dead=delete(@Wrestlers{Champ}); print values(%Wrestlers); print "\n\n"; print "This guy is dead: " . $Dead; Here we have: Brutus Beefcake Big John Stud CM Punk Chavo Guerrero Brutus Beefcake Big John Stud Chavo Guerrero This guy is dead: CM Punk And finally, we come back to our scenario where both Chavo and CM Punk die. Now we would like to add them to a growing list of dying wrestlers. Since seeing is believing, here is the eye-catching code: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); print values(%Wrestlers); print "\n\n"; @Dead=delete(@Wrestlers{Champ,Chump}); print values(%Wrestlers); print "\n\n"; print "These guys are dead: " . @Dead[0] . @Dead[1]; This will delete the records for 'Champ' and 'Chump' and store them in the list @Dead. When we run this program we get the following printout: Brutus Beefcake Big John Stud CM Punk Chavo Guerrero
Brutus Beefcake Big John Stud These guys are dead: CM Punk Chavo Guerrero One final note. Had you tried to write out both values in the @Dead list like so: print "These guys are dead: " . @Dead; You would have been given the sentence: These guys are dead: 2 Instead of printing the values, it would have printed the number of elements. Why that is, I am not certain. Well that's all the time we have for this one. Be sure to stop by next time as we continue talking about hashes and go into those multidimensional lists you've been hearing so much about. Till then...
blog comments powered by Disqus |
|
|
|
|
|
|
|