Questions And Answers

More Tutorials

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)) {

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


In this page (written and validated by ) you learned about Perl Associative Arrays (Hashes) . What's Next? If you are interested in completing Perl tutorial, your next topic will be learning about: Perl Regular expressions.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue:

Share On:

Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using, you agree to have read and accepted our terms of use, cookies and privacy policy.