What are hashes of arrays in Perl?

Overview

Hashes of arrays in Perl are used when we want to access an array using an identifier rather than indices. It is an easier method to sort multiple arrays and classify them.

Examples

General syntax

The following example will help you understand the general syntax for hashes of arrays. First, we populate a hash with arrays detailing seasons, days of a week, and weeks of a month. Then, to print each of the arrays and their elements, we use a for loop to loop through the keys.

%HashesOfArrays = (
seasons => ["summer", "autumn", "winter", "spring"],
days => ["Monday", "Tuesday", "Wednesday","Thursday", "Friday","Saturday","Sunday"],
week => [1,2,3,4],
);
for $types ( keys %HashesOfArrays )
{ print "$types: @{ %HashesOfArrays{$types} }\n"; }

Pushing elements to a hash of arrays

You can use push to add elements to a key of the hash. As shown below, we first print the initial hashes of arrays and then push new elements to the keys seasons and days.

%HashesOfArrays = (
seasons => ["summer", "autumn"],
days => ["Monday", "Tuesday", "Wednesday","Thursday", "Friday"],
week => [1,2,3,4],
);
print "before pushing new elements \n";
for $types ( keys %HashesOfArrays )
{ print "$types: @{ %HashesOfArrays{$types} }\n"; }
push @{ $HashesOfArrays{seasons} }, "winter", "spring";
push @{ $HashesOfArrays{days} }, "Saturday","Sunday";
print "\nafter pushing new elements \n";
for $types ( keys %HashesOfArrays )
{ print "$types: @{ %HashesOfArrays{$types} }\n"; }

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved