Skip to content

Perl Hashes Guide — Key-Value Data Structures and Hash Operations

DodaTech Updated 2026-06-28 3 min read

In this tutorial, you will learn about Perl Hashes Guide. We cover key concepts, practical examples, and best practices to help you master this topic.

Perl hashes (%hash) are unordered associative arrays mapping unique string keys to scalar values -- offering O(1) lookup, built-in iteration, and the ability to store references for nested data structures.

Creating Hashes

use strict;
use warnings;

# Simple hash
my %person = (
    name => "Alice",
    age  => 30,
    city => "New York"
);

# Fat comma => auto-quotes left side
# Equivalent to:
my %person2 = ("name", "Alice", "age", 30, "city", "New York");

Accessing Elements

my %config = (
    host    => "localhost",
    port    => 8080,
    debug   => 1,
    timeout => 5000
);

# Access single element (uses $ prefix)
print $config{host};     # localhost
print $config{port};     # 8080

# Check existence
if (exists $config{debug}) {
    print "Debug is " . $config{debug} . "\n";
}

# Delete
delete $config{timeout};

Iterating Over Hashes

my %scores = (
    Alice => 95,
    Bob   => 87,
    Carol => 92
);

# Keys and values
my @students = keys %scores;
my @scores = values %scores;

# Iterate over key-value pairs
while (my ($name, $score) = each %scores) {
    print "$name scored $score\n";
}

# Iterate over sorted keys
for my $name (sort keys %scores) {
    print "$name: $scores{$name}\n";
}

Hash Operations

my %hash1 = (a => 1, b => 2);
my %hash2 = (c => 3, d => 4);

# Merge hashes
my %merged = (%hash1, %hash2);

# Count keys
my $count = keys %hash1;  # 2

# Clear hash
%hash1 = ();

# Check if hash is empty
if (keys %hash2 == 0) {
    print "Empty\n";
}

Nested Data Structures

# Hash of hashes
my %employees = (
    alice => {
        name  => "Alice Smith",
        dept  => "Engineering",
        title => "Senior Dev"
    },
    bob => {
        name  => "Bob Jones",
        dept  => "Marketing",
        title => "Manager"
    }
);

# Access nested
print $employees{alice}{title};  # Senior Dev

# Hash of arrays
my %class = (
    math    => ["Alice", "Bob"],
    science => ["Carol", "Dave", "Eve"]
);
print $class{math}[0];  # Alice

Common Mistakes

1. Confusing $hash{key} with %hash{key}

Individual elements use $ prefix: $hash{key}. The whole hash uses % prefix.

2. Not using quotes for non-simple keys

Keys with special characters use quotes: $hash{"my key"}.

3. Forgetting exists before access

Accessing a non-existent key returns undef. Check with exists to distinguish from a key set to undef.

Practice Questions

1. How do you add a new key-value pair? $hash{new_key} = "value"; -- just assign to the new key.

2. How do you iterate over a hash? Use while (my ($key, $value) = each %hash) or for my $key (keys %hash).

3. How do you check if a key exists? exists $hash{key} returns true if the key is in the hash, even if its value is undef.

FAQ

{{< faq question="Are Perl hashes ordered?" >}} No, hash elements are unordered. Insertion order is not preserved. Use the Tie::IxHash module for ordered hashes. {{< /faq >}}

{{< faq question="What values can be stored in hashes?" >}} Scalars (numbers, strings, undef) and references. References allow nested data structures like hashes of hashes or arrays of hashes. {{< /faq >}}

{{< faq question="How do I sort a hash?" >}} Sort by key: sort keys %hash. Sort by value: sort { $hash{$a} cmp $hash{$b} } keys %hash for strings or <=> for numbers. {{< /faq >}}

What's Next

Now learn about Perl's powerful regular expressions.

Topic Description Link
Regex Regular expressions {{< ref "06-regex" >}}
Subroutines Defining and using functions {{< ref "07-subroutines" >}}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro