Monday, 23 December 2013

PS_06_Perl - Associative Arrays (Hashes)

Associative Arrays (Hashes)

A hash (or associative array) is an unordered set of key/value pairs whose elements are indexed by their keys. Hash variable names have the form %foo.

Hash Variables and Literals
A literal representation of a hash is a list with an even number of elements (key/value pairs, remember?).
%foo = qw( fred wilma barney betty );
%foo = @foolist;

To add individual elements to a hash, all you have to do is set them individually:
$foo{fred} = “wilma”;
$foo{barney} = “betty”;

You can also access slices of hashes in a manner similar to the list case:
@foo{“fred”,”barney”} = qw( wilma betty );

Hash Functions
The keys function returns a list of all the current keys for the hash in question.
@hashkeys = keys(%hash);

As with all other built-in functions, the parentheses are optional:
@hashkeys = keys %hash;

This is often used to iterate over all elements of a hash:
foreach $key (keys %hash) {
print $hash{$key}.”\n”;
}

In a scalar context, the keys function gives the number of elements in the hash. Conversely, the values function returns a list of all current values of the argument hash:
@hashvals = values(%hash);

The each function provides another means of iterating over the elements in a hash:
while (($key, $value) = each (%hash)) {
statements;
}

You can remove elements from a hash using the delete function:
delete $hash{‘key’};

No comments :

Post a Comment