Robert's Perl Tutorial

http://www.sthomas.net/roberts-perl-tutorial.htm


The Basics

Very, very useful. First, a quick recap on arrays. Arrays are an ordered list of scalar variables, which you access by their index number starting at 0. The elements in arrays always stay in the same order.

Hashes are a list of scalars, but instead of being accessed by index number, they are accessed by a key. The tables below illustrate the point:

@myarray
Index No. Value
0 The Netherlands
1 Belgium
2 Germany
3 Monaco
4 Spain
%myhash
Key Value
NL The Netherlands
BE Belgium
DE Germany
MC Monaco
ES Spain

So if we want 'Belgium' from @myarray and also from %myhash , it'll be:

print "$myarray[1]";
print "$myhash{'BE'}";

Notice that the $ prefix is used, because it is a scalar variable. Despite the fact it is part of a list, it is still a scalar variable. The hash syntax is simply to use braces { } instead of square brackets.

So why use hashes ? When you want to look something up by a keyword. Suppose we wanted to create a program which returns the name of the country when given a country code. We'd input ES, and the program would come back with Spain.

You could do it with arrays. It would be messy however. One possible approach:

  1. create @country , and give it values such as 'ES,Spain'
  2. Itierate over the entire array and
  3. split each element of the array, and check the first result to see if it matches the input
  4. If so, return the index
@countries=('NL,The Netherlands','BE,Belgium','DE,Germany','MC,Monaco','ES,Spain');

print "Enter the country code:";
chop ($find=<STDIN>);

foreach (@countries) {
        ($code,$name)=split /,/;
        if ($find=~/$code/i) {
                print "$name has the code $code\n";
        }
}

Complex and slow. We could also store a reference to another array in each element of @countries , but that is not efficient. Whatever way we choose, you still need to search the whole thing. And what if @countries is a big array ? See how much easier a hash is: