HomePerl Programming Perl: A Continuing Look at Hashes and Multidimensional Lists
Perl: A Continuing Look at Hashes and Multidimensional Lists
Welcome to the ninth installment in our look at working with hashes and lists in Perl. In our previous article we learned how to add records to a hash, replace them, and delete the values inside of them. In this article we will learn how to check whether records reside within our hashes, write the data within a hash to a file, and create multidimensional lists.
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: