Also known as 'hashes' or 'keyed arrays', associative arrays provide a way to link two pieces of data together in a simple yet surprisingly efective data structure. One piece of data, called the key is the index into the array. The second item, the value, is the data to be retrieved when the key is provided.
An empty hash is created simply by referencing it, as with any other Perl variable…
my %CustomerReferences;
or
use vars qw / %InvoiceNumbers / ;
Adding data is a simple as any other assignment, except that you need to provide both the key and the value…
$CustomerName = "Acme Bicycles"; $CustomerID = "AB20070324"; $CustomerAccountLookup{$CustomerName} = $CustomerID;
…after which, %CustomerAccountLookup contains an element where the key is 'Acme Bicycles' associated with a value of 'AB20070324'. The power of this arrangement is that you can now retrieve the value, simply by supplying the key. So the code…
$FindThis = "Acme Bicycles"; WriteMessage("Requested account is " . $CustomerAccountLookup{$FindThis}", $Verbose);
…will print out “AB20070324”.
The strength of associative arrays can be found when you need to reference large amounts of data by nomenclature that you don't know until run-time. Consider this trivialisation of a real world application…
$CustomerCode = "AB20070324"; $TransactionDate = 20080924; $InvoiceNumber = "GH730419"; $Amount = 318.47; $Key = $CustomerCode . "_" . $TransactionDate; $Value = $InvoiceNumber . "_" . $Amount; $SalesByDay{$Key} = $Value;
Imagine that the example is just one of several thousand. You can retrieve all the invoice amounts for a customer on a particular day simply by supplying the customer's ID and the date as a key.