Hashes

Contents | Up | Prev | Next

# 2. Hashes

Hashes can be used to map a set of keys, each to his own value. Using a hash one can retrieve the value associated with each key, as well as get a list of all the keys present in the hash.

To assign or retrieve the value of the key `$mykey` in the hash `$myhash` one uses the `$myhash{$mykey}` convention. To check if a key exists in a hash one should type `exists($myhash{$mykey})` which in turn returns a boolean value that corresponds to its existence.

An array whose elements are the keys present in the hash can be retrieved by typing `keys(%myhash)`. Here's a short example, that runs a simple bank, that will illustrate this functionality:

    # Initialize the valid operations collection
    $ops{'create'} = 1;
    $ops{'deposit'} = 1;
    $ops{'status'} = 1;
    $ops{'exit'} = 2;

    while (1)
    {
        # Get a valid input from the user.
        while (1)
        {
            print "Please enter what you want to do:\n";
            print "(" . join(", ", keys(%ops)) . ")\n";

            $function = <>;
            chomp($function);

            if (exists($ops{$function}))
            {
                last;
            }
            print "Unknown function!\n Please try again.\n\n"
        }

        if ($function eq "exit")
        {
            last;
        }

        print "Enter the name of the account:\n";
        $account = <>;
        chomp($account);
        if ($function eq "create")
        {
            if (! exists($bank_accounts{$account}))
            {
                $bank_accounts{$account} = 0;
            }
        }
        elsif ($function eq "status")
        {
            if (! exists ($bank_accounts{$account}) )
            {
                print "Error! The account does not exist.\n";
            }
            else
            {
                print "There are " . $bank_accounts{$account} .
                    " NIS in the account.\n";
            }
        }
        elsif ($function eq "deposit")
        {
            if (exists($bank_accounts{$account}) )
            {
                print "How much do you wish to deposit?\n";
                $how_much = <>;
                chomp($how_much);
                $bank_accounts{$account} += $how_much;
            }
        }
        print "\n";
    }

The following example, which is considerably shorter, uses a hash to find out if a list of strings contains only unique strings:

    while($string = <>)
    {
        chomp($string);
        if (exists($myhash{$string}))
        {
            print "The string \"" . $string . "\" was already encountered!";
            last;
        }
        else
        {
            $myhash{$string} = 1;
        }
    }

Contents | Up | Prev | Next