Perl: the Perl hash
The tutor asks, “Will the real hash please stand up?”
I’ve been hearing about hashtags for a few years now. At first, I wondered why people were suddenly showing much interest in data structures.
A data structure is a way of storing data that suggests relationships between the entries. An array is a data structure: it stores a list of elements such that each has a position (or index) as well as a value.
In comp sci, another term for hash is associative array. A hash stores values not by position, but by descriptor, also called key.
In Perl, the hash symbol is %. Here’s a short Perl program to illustrate a hash:
#!/usr/bin/perl
%maritimecapitals=(‘NB’,’Fredericton’,’NS’,’Halifax’,’PEI’,’Charlottetown’);
print “Hello. Which Maritime capital would you like to know?\n\n”;
print “Key in NS for Nova Scotia, NB for New Brunswick, or\n\n”;
print “PEI for Prince Edward Island.\n\n”;
$prov=<STDIN>;
chomp $prov;
print “The capital of $prov is $maritimecapitals{$prov}.\n\n”;
Let’s imagine you call this program maricaps.txt, then, from its directory, you key in
perl maricaps.txt
The program should politely ask you which Maritime province’s capital you want to know. Let’s imagine you key in NS. Hopefully, you’ll receive the reply
The captial of NS is Halifax.
There is much more to say about this topic. Look for more here soon.
HTH:)
Sources:
McGrath, Mike. Perl in easy steps. Southam: Computer Step, 2004.
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.