Perl Programming Page 2 - Perl: A Continuing Look at Hashes and Multidimensional Lists |
You can use the if statement in a manner that is opposite to the way the unless function was used. In this situation, the print function will execute if there are values in the %Wrestlers hash: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); if(%Wrestlers) { print "Hey, Look at all my records!"} Giving us the result: Hey, Look at all my records! If there were no records in %Wrestlers, then nothing would have happened. To fix this, we can do one of two things. The most obvious would be to use an "else" clause with our if statement, like so: #!/usr/bin/perl %Wrestlers=(); if(%Wrestlers) { print "Hey, Look at all my records!"} else {print "Hey, who stole all my records?!?"} Now if the hash contains data it will print one thing, and if it doesn't, it will print another. Since there is no data in our hash, this is the result: Hey, who stole all my records? The second way to get a result whether or not there is data is to use the if statement and unless function together, like so: #!/usr/bin/perl %Wrestlers=(Champ=> ' CM Punk ', Chump => ' Chavo Guerrero ', OldSkool=> ' Big John Stud ', Boof=> ' Brutus Beefcake '); if(%Wrestlers) { print "Hey, Look at all my records!"} unless(%Wrestlers) { print "Hey, have you guys seen my records?"} Which works in the same manner as our previous example. Which you use is up to you.
blog comments powered by Disqus |
|
|
|
|
|
|
|