Perl: Storing arrays in hashes

Let’s start with a quote from ‘Learning Perl‘:

What Is a Hash?

A hash is a data structure, not unlike an array in that it can hold any number of values and retrieve them at will. But instead of indexing the values by number, as we did with arrays, we’ll look up the values by name. That is, the indices (here, we’ll call them keys ) aren’t numbers, but instead they are arbitrary unique strings



Our goal: We want to store an array as a value in the hash instead of saving a single value.

Let’s write some code:

use strict;
use warnings;

my %hash = ();
my @array = (1, 2, 3, 4, 5);
my $aref = \@array;
$hash{"Testing"} = $aref;
print join " ",@{$hash{"Testing"}};

This piece of Perl code stores an array as a value in a hash and adds a new element to the array.

Now let’s analyze the code.

First we create an empty hash and we create an array and initialize it.

my %hash = ();
my @array = (1, 2, 3, 4, 5);

Now we need a reference of our array (so that we can store it as a value in the hash):

my $aref = \@array;

reference to array
In the next step below we actually do what we wanted. Storing an array into a hash value. We create a key in our hash called “Testing” and store the reference of our array in the value field.

$hash{"Testing"} = $aref;

We can see that the reference of our array ($aref) is pointing to our array so we can access the array in our hash. :)

This code adds a new element with value '6' to our array:



# Gives the value of key Testing, it's the reference to the array

# Dereference it with {} to access the array (that's why we have an @ at the begin)

I hope that helped :)