Perl Hashes

Thanks for stopping by for this seventh part in the series on Perl Lists and Hashes. Here we will discuss working with a new way to store data known as a Hash. We’ll cover the basics, such as how to create them, and how to locate data within them. You’ll learn to add records, remove records, and much more. If there is time, we will also cover multidimensional lists.

In our previous article we covered the remaining List::Util subroutines. We used min(list) to find the minimum numeric value in a list. We also worked with its brother, the minstr(list), which as you will recall found the smallest string value in a list. We learned that uppercase letters hold a lower value, surprisingly, then lowercase ones. We also learned to use shuffle to randomly sort our lists, and sum(list) to sum up the numeric values in our lists.

Hash…Not What It Sounds Like

If you have worked with Access or Excel, or any grid-type program, you are familiar with the concept of a hash. These aren’t exactly like a hash mind you, but a similar idea. Whereas with a typical list, you refer to the values stored in them by referencing their element or index number, like so:

  array[0]

with hashes you look them up with their key. When you create an element in a hash, you assign it a key value. That key, plus the value, creates a record. If that is still confusing to you, never fear: after our example it should be crystal clear.

{mospagebreak title=Creating A Hash}

If you are familiar with other programming languages, then you will know that a hash is similar to an associative array. Before we create our first hash, there are a few rules you must learn. The first one is the naming convention. Hashes are named like other lists, except that they start with a percent sign (%) rather than the ampersand (@). When you refer to a key you use the curly braces {}, as opposed to parentheses as in regular lists. When you create the hashes, you use parentheses. Okay, enough blabbering; let’s create our first hash:


#!/usr/bin/perl

%Brownies = (1,’Chocolate’, 2,’Fudge’,3,’Vanilla’,4,’Peanut Butter’);

In the above example we created four key-value pairs. If we printed out the hash, this is how we would do so, and also, the result:


#!/usr/bin/perl

%Brownies = (1,’Chocolate’, 2,’Fudge’,3,’Vanilla’,4,’Peanut Butter’);

print %Brownies;

Which prints:

  4Peanut Butter1Chocolate3Vanilla2Fudge

Not quite what we expected right? You will note that hashes are not ordered lists and will not necessarily print in the order you enter them. Also, you will notice that the key gets printed along with the value when we print in this manner. We will learn in a short bit how to print only the values when we want to print the entire hash.

{mospagebreak title=Printing from a Hash}

There are several print methods that you can use with hashes. The first we will learn about is printing individual values from a hash. Here, we will use our previous list of different types of brownies to print from:


#!/usr/bin/perl

%Brownies = (1,’Chocolate ‘, 2,’Fudge ‘,3,’Vanilla ‘,4,’Peanut Butter

‘);

print $Brownies{1};

You will note that we use $Brownies in our print statement instead of %Brownies. This is because we are only printing a single value, and thus it becomes a variable. The result of this is:

  Chocolate

If we wanted to print more than one value from the hash, we would change the $Brownies variable to @Brownies, since there will be more than one value in it. Here is how we return two or more values:


#!/usr/bin/perl

%Brownies = (1,’Chocolate ‘, 2,’Fudge ‘,3,’Vanilla ‘,4,’Peanut Butter

‘);

print @Brownies{1,2};

This simplistic code returns the following:

  Chocolate Fudge

Note that the keys that refer to your values don’t have to be numbers. Here, we will use some text instead:


#!/usr/bin/perl

%HowItIs = (Dumb,’You ‘, Fat,’YoMama ‘,UglyGenius,’James Payne

‘,Nerd,’PHP Programmers’);

print @HowItIs{Dumb,Fat,Nerd};

This code assigns the value “You” to the key Dumb, “YoMama” to Fat, and so forth. When we run this program, it prints the following:

  You YoMama PHP Programmers

Another thing to remember is that your keys may not equal the same value, but the value inside your keys can. Let’s say that in addition to being an ugly genius, I am also a nerd. Here is how I could assign myself to two keys:


#!/usr/bin/perl

%HowItIs = (Dumb,’You ‘, Fat,’YoMama ‘,UglyGenius,’James Payne

‘,Nerd,’James Payne’);

print @HowItIs{UglyGenius,Nerd};

The result is of course:

  James Payne James Payne

{mospagebreak title=Printing All the Values or Keys in a Hash}

As we saw earlier, you cannot simply print all the values in a hash using the print command. You could, but then you would also get the keys associated with those values as well, which you may not want. Perl has a handy function, called “values,” that can help you achieve this goal:


#!/usr/bin/perl

%HowItIs = (Dumb,’You ‘, Fat,’YoMama ‘,UglyGenius,’James Payne

‘,Nerd,’James Payne ‘);

print values(%HowItIs);

This prints out just the values in the hash:

  James Payne James Payne YoMama You

If we wanted to print out all the keys, and not the values, we can do that also, using another function, “keys”. Here it is in code:


#!/usr/bin/perl

%HowItIs = (Dumb,’You ‘, Fat,’YoMama ‘,UglyGenius,’James Payne

‘,Nerd,’James Payne’);

print sort(keys(%HowItIs));

Note that I sorted this print out also:

  DumbFatNerdUglyGenius

And of course if we wanted a list of both keys and values in a sentence, we can do that as well with the following nifty little program:


#!/usr/bin/perl

%HowItIs = (Dumb,’You ‘, Fat,’YoMama ‘,UglyGenius,’James Payne

‘,Nerd,’James Payne’);

@All = keys(%HowItIs);

foreach $ItIs(@All)

{print "The key for $HowItIs{$ItIs} is $ItIsn"};

Which gives us the following result:

  The key for James Payne is Nerd

  The key for James Payne is UglyGenius

  The key for Yomama is Fat

  The Key for You is Dumb

{mospagebreak title=Alternative Methods for Creating Hashes}

There are other ways to create hashes as well. In this next example we will use one of them. Note though that this only works for Perl 5 and later. Here, we will use the => operator to assign values:


#!/usr/bin/perl

%HowItIs = (Dumb=>’You ‘, Fat=>’YoMama ‘,UglyGenius=>’James Payne

‘,Nerd=>’James Payne’);

print $HowItIs{Dumb};

This prints out:

  You

There really is no difference between this and the original method as far as I know. Some people say this way is easier to read, but it is really up to personal preference.

You could also create an empty hash if you wanted, and assign values to it later:


#!/usr/bin/perl

%HowItIs = ();

We’ll learn how to add to it in a bit.

What if we want to create a hash from another hash? That too is a simple process:


#!/usr/bin/perl

%HowItIs = (Dumb=>’You ‘, Fat=>’YoMama ‘,UglyGenius=>’James Payne ‘,Nerd=>’James Payne ‘);

%HowItWas = %HowItIs;

print values(%HowItWas);

print "nn";

print keys(%HowItWas);

In the above example, we create our %HowItIs hash and assign it some values. Next, we create another hash named %HowItWas, and add the values from %HowItIs to it. We then print out first the values, then the keys to verify that it worked. The result:

  James Payne James Payne YoMama You

  UglyGeniusNerdFatDumb

If we only wanted to add a few of the values to our newly created hash, we could do so in the following manner:


#!/usr/bin/perl

%HowItIs = (Dumb=>’You ‘, Fat=>’YoMama ‘,UglyGenius=>’James Payne

‘,Nerd=>’James Payne ‘);

%HowItWas = @HowItIs{Dumb,Fat};

print values(%HowItWas);

print "nn";

print keys(%HowItWas);

The result?

  YoMama

  You

We aren’t limited to creating just other hashes with our hashes. We can also create variables:


#!/usr/bin/perl

%HowItIs = (Dumb=>’You ‘, Fat=>’YoMama ‘,UglyGenius=>’James Payne

‘,Nerd=>’James Payne ‘);

$HowItWas = @HowItIs{Dumb};

print $HowItWas;


Which gives us:

  You

And we can also create lists as well:

#!/usr/bin/perl


%HowItIs = (Dumb=>’You ‘, Fat=>’YoMama ‘,UglyGenius=>’James Payne

‘,Nerd=>’James Payne ‘);

@HowItWas = @HowItIs{Dumb,Fat,Nerd};

print @HowItWas;

Here we are given:

  You YoMama James Payne

Conclusion

We covered a lot of ground in this article, however, there is much more to go. In our next tutorial we will learn to add records to hashes, remove them, check to see if a record already exists, create multidimensional lists, and much, much more. So be sure to stop by often.

Till then…

[gp-comments width="770" linklove="off" ]

chat