Perl Programming Page 3 - Perl: Another Round with Hashes |
But what if we don't want to replace CM Punk just yet? Perhaps they are going to decide the new champ via a Wrestlemania contest or something. In this case, we may wish to delete the record for now and add it later. Deleting a record in a hash is a simple matter. To do so, we simply use the conveniently built-in delete() function: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); print values(%Wrestlers); print "\n\n"; delete($Wrestlers{Champ}); print values(%Wrestlers); Here, once more values are assigned to a hash and printed out. Then we use delete() to remove a record by specifying which record to remove. In this instance we removed the value in “Champ.” When we print this out, we get the following result: Brutus Beefcake Big John Stud CM Punk Chavo Guerrero Brutus Beefcake Big John Stud Chavo Guerrero Now let's say that CM Punk and Chavo Guerrero happened to be riding in the same car and both of them died. If we wanted to delete multiple records from our hash, we could do so in the following manner: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); print values(%Wrestlers); print "\n\n"; delete(@Wrestlers{Champ,Chump}); print values(%Wrestlers); As you can see, this is very similar code. The only differences really are the addition of the record Chump, separated by a comma, and the change of the variable $Wrestlers to a list, or @Wrestlers, since we are removing more than one record. Here are our results: Brutus Beefcake Big John Stud CM Punk Chavo Guerrero Brutus Beefcake Big John Stud The wrestling world sure is shrinking.
blog comments powered by Disqus |
|
|
|
|
|
|
|