Perl Programming Page 2 - Perl: Another Round with Hashes |
There are several ways to add multiple records to a hash. Here, we are going to add Brutus “the Barber” Beefcake to our already created hash: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero '); $New=" Big John Stud "; $Boof=" Brutus Beefcake "; print values(%Wrestlers); print "\n\n"; $Wrestlers{OldSkool}=$New; $Wrestlers{Beef}=$Boof; print values(%Wrestlers); Note that each time, $Wrestlers holds our values. When we print this code we get the following result: Brutus Beefcake Big John Stud CM Punk Chavo Guerrero Replacing a Record in a Hash Replacing a record in a hash with another record is pretty similar to adding a record. In our previous examples we stated that CM Punk was the champ (well we assigned his value to the champ key at any rate). But what happens if CM dies in a horrible car accident and the title is given to someone else? Here is how we would replace the value in the key 'champ': #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); $New=" The Nature Boy Ric Flair "; print values(%Wrestlers); print "\n\n"; $Wrestlers{Champ}=$New; print values(%Wrestlers); Here, the %Wrestlers hash has been created and assigned a bunch of key-pair values. Next, we create a variable named $New to hold a given value. Next we print out the values of our %Wrestlers hash, then assign the key “Champ” a new value, said value being the one stored in $New. Finally, we print out the value of %Wrestlers once more to confirm that the replace took place. This works because Perl sees the “Champ” key and searches in the hash for it. If it finds it, it replaces its value with the one you specify. If not, it adds it to the hash. You can achieve the same without variables of course: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); print values(%Wrestlers); print "\n\n"; $Wrestlers{Champ}="The Nature Boy Ric Flair"; print values(%Wrestlers); Giving us the same result as above: Brutus Beefcake Big John Stud CM Punk Chavo Guerrero Brutus Beefcake Big John Stud The Nature Boy Ric Flair Chavo Guerrero
blog comments powered by Disqus |
|
|
|
|
|
|
|