Perl Hashes - Alternative Methods for Creating Hashes (
Page 5 of 5 )
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 "\n\n";
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 "\n\n";
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...