Perl Programming Perl: A Continuing Look at Hashes and Multidimensional Lists |
Has Anyone Seen My Records? Sometimes it is necessary to check to see if a hash holds any values. There are many ways to do this, such as printing our the entire hash, but another method is to use the "unless" function and "if" statement. In the following code we use unless to see if there are any values in our hash. If so, nothing happens. If not, we get some printed text: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); unless(%Wrestlers) { print "Hey, have you guys seen my records?"} In the above code we assigned some key-pair values to our %Wrestlers hash. We then used a statement that basically says, "unless there are values in %Wrestlers, print some text." Since there are values in %Wrestlers, in this instance nothing happens. Now let's modify the code a little by removing the values in our hash: #!/usr/bin/perl %Wrestlers=(); unless(%Wrestlers) { print "Hey, have you guys seen my records?"} When we run the program this time, the print statement is triggered because there are indeed no values in %Wrestlers. Here is the result: Hey, have you guys seen my records?
blog comments powered by Disqus |