How to create an array of hashes in Perl?

Question

How to create an array of hashes in Perl?

Creating an array of hashes in Perl is a common technique when you want to manage a collection of records or structured data, where each element in the array is a hash containing key-value pairs. This data structure is very powerful and versatile for representing complex information such as database rows, configuration sets, or JSON-like objects.

Understanding Perl Data Structures: Arrays and Hashes

In Perl, arrays are ordered lists denoted with the @ sigil, and hashes (associative arrays) are key-value stores denoted with %. To create an array of hashes, you essentially have an array where each element is a reference to a hash. This leverages Perl’s powerful referencing system.

Because hashes can be large or complex, it’s typical to store references to hashes inside an array rather than store hashes directly. This results in an array of hash references, where each element is a scalar ($) holding a reference.

How to Create and Use an Array of Hashes

Here is a step-by-step example demonstrating the creation and usage of an array of hashes, including how to access and modify elements.

#!/usr/bin/perl
use strict;
use warnings;

# Create an array to hold hash references
my @array_of_hashes;

# Push hash references into the array
push @array_of_hashes, { name => 'Alice', age => 30, city => 'London' };
push @array_of_hashes, { name => 'Bob',   age => 25, city => 'Paris' };
push @array_of_hashes, { name => 'Carol', age => 27, city => 'Berlin' };

# Access and print data from the array of hashes
for my $person (@array_of_hashes) {
    # Dereference hash reference using %{$person}
    print "Name: $person->{name}, Age: $person->{age}, City: $person->{city}\n";
}

# Modify an entry: Change Bob's city
$array_of_hashes[1]{city} = 'Rome';

print "\nAfter update:\n";
foreach my $person (@array_of_hashes) {
    print "Name: $person->{name}, Age: $person->{age}, City: $person->{city}\n";
}

Explanation of Key Concepts

  • Array of hash references: Each entry is a scalar ($person) holding a reference to a hash (e.g., { name => ..., age => ... }).
  • Dereferencing: To access hash elements inside the array, you use the arrow operator ->: $array_of_hashes[0]{name} is equivalent to ${$array_of_hashes[0]}{name}.
  • Sigils & context: The @ sigil denotes the array @array_of_hashes, but individual elements are scalars (references), hence use $array_of_hashes[index] to get the scalar.
  • TMTOWTDI (“There’s More Than One Way To Do It”): You can initialize the array directly, like my @arr = ( {..}, {..}, {..} ); or push references later as shown.

Common Gotchas

  • Don't try to store a hash directly in an array element without using a reference; that only stores a flattened list, which leads to unexpected results.
  • Remember references are scalars; when accessing an element in the array, you must use $, not @.
  • Using the wrong sigil or dereferencing incorrectly can cause runtime errors. For instance, $array_of_hashes[0]{name} is correct, but @array_of_hashes[0]{name} is not.
  • From Perl 5.10, you can also use the say function from feature for convenience (requires use feature 'say';).

In summary, the array of hashes pattern is idiomatic and powerful in Perl to manage structured multi-element data collections. Using references lets you build nested data structures easily, applying Perl’s flexible TMTOWTDI philosophy.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 8ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Name: Alice, Age: 30, City: London
Name: Bob, Age: 25, City: Paris
Name: Carol, Age: 27, City: Berlin

After update:
Name: Alice, Age: 30, City: London
Name: Bob, Age: 25, City: Rome
Name: Carol, Age: 27, City: Berlin
STDERR
(empty)

Was this helpful?

Related Questions