Sophisticated variables: hashes
Previous  Top  Next

Hashes are a little more complex but can be more useful if needed. A Hash consists not only of one but two values each - a KEY and a VALUE.
To initialize a hash write:

%myhash = (
      "Name" => "Ingmar Köcher",
      "Hobby" => "Nothing and everything",
      "shoe size" => 10
    );

or

$myhash{'Name'} = "Ingmar Köcher";
$myhash{'Hobby'} = "Nothing and everything";
$myhash{'shoe size'} = 10;

and now an example of how to make use of this:

1: %myhash = ("Name" => "Ingmar Köcher","Hobby" => "Nothing and everything", "shoe size" => 10);
2:
3: foreach $key (keys %myhash)
4: {
5:     print $key.": ".$myhash{$key}."\n";
6: }

This will show up like:

Name: Ingmar KÖCHER
Hobby: Nothing and everything
shoe size: 10

Here we make use of the keys feature by iterating through all items in the hash. After the key is assigned to $key, we can then retrieve the value by printing $myhash{$key}.