A review of Perl hashes…

Some of you had some problems with the exercise on Perl hashes, this is a short review about them.

What a hash is

An array is an ordered list of scalars, right? Well a hash is an (unordered) list of pairs of scalars. One is called key, and has to be unique, the other is its value. Consider that we want to know the name of an Italian provincia given the short code (or at least “quelle con un nome sdrucciolo ad esempio Padova, Genova“), we can create an hash like:

%provName = (
 'PD' => 'Padova', 
 'GE' => 'Genova', 
 'TA' => 'Taranto',
 'BG' => 'Bergamo', 
 'TP' => 'Trapani'
 );

This syntax is to create a hash from zero. Its a comma separated list of pairs, each pair is in the form KEY => VALUE. If we want to print the extended form of PD we can invoke $provName{‘PD’}. If we have the shortcode stored in the $provincia variable, we can type $provName{$provincia} to do the same.

How to “populate” an hash

Most of the times we want to add new things to an hash during a loop. Consider the previous hash, we want to add a new pair of key-value. Here you are:

$provName{'BR'} = 'Brindisi';

In this case we don’t use the arrow notation (=>) because we are simply assigning a value to a variable, like $prov = ‘Something’, with the difference that the variable in this case is a new hash item. Of course, if you have variables with key and/or value, you ca

Reading an hash with foreach

if we simply want to process (e.g. print) all the hash values:

foreach $key (keys %provName) {
  print " $key ---> $provName{$key} \n";
}

In this case we use the “keys %hash” function that returns an array with all the keys. This means that we can use the usual foreach cycle. Now at each cycle $key contains the current key, and thus $hash{$key} its value.

Tagged ,

2 thoughts on “A review of Perl hashes…

  1. […] also have a post on Perl hashes, in case you want to better understand its […]

  2. […] uno script chiamato siamo_noi.pl in cui creare un hash che contenga almeno 4 elementi, del tipo “geno-1″ -> “Nome Cognome”. In […]

Leave a Reply

Your email address will not be published. Required fields are marked *