Perl Programming Page 3 - Perl: A Continuing Look at Hashes and Multidimensional Lists |
Checking whether a hash contains any data whatsoever is good, but what if we need something a little more specific? For that we could use our good old buddy the exist() function, which, as the name implies, checks to see if a specific key exists. Here it is in action, checking whether the “Champ” is in our hash: #!/usr/bin/perl %Wrestlers=(Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); unless(exists($Wrestlers{Champ})) { print "Where is the champ?"} Since the “Champ” key does not exist, the print function is triggered, resulting in: Where is the champ? And of course, just as before, we can use if to check if the value is in the hash and print a result if it is: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); if(exists($Wrestlers{Champ})) { print "I see the champ!"} Giving us a very enthusiastic: I see the champ! We can also use an if-else to print something out if the value does not exist, or use the if statement and the unless to achieve the same effect. Here they both are in the following examples: #!/usr/bin/perl %Wrestlers=(Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); if(exists($Wrestlers{Champ})) { print "I see the champ!"} else {print "Has anyone seen the champ?"} or, the same result but written differently: #!/usr/bin/perl %Wrestlers=(Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); if(exists($Wrestlers{Champ})) { print "I see the champ!"} unless(exists($Wrestlers{Champ})) { print "Has anyone seen the champ?"} Both of these would give us the same result: Has anyone seen the champ?
blog comments powered by Disqus |
|
|
|
|
|
|
|