Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 43 ยท Arrays and Hashes

Hashes

Learn Perl hashes: key/value pairs, exists and delete, keys, values and each, hash slices, counting words, and how a hash behaves in list context.

An array finds things by position. A hash finds things by name. It stores pairs of a key and a value, and looks up any value instantly by its key, no matter how many pairs there are. Hashes are how Perl programs hold records (name, age, email), word counts, settings, lookup tables and indexes. If arrays are the workhorse of Perl, hashes are its secret weapon.

Hash variables start with the % sigil. Just as with arrays, picking out one value changes the sigil to $, because the value is a scalar: $age{alice}. Keys are always strings, and values are any scalars. Hashes have no guaranteed order, which is the most important thing to remember about them.

Perl is not installed on this site, so the Perl listings are read-only; their outputs come from real runs of Perl 5.42. The TryIt blocks use Python dictionaries as a stand-in that models the same ideas. If you are new to arrays, read Arrays first.

Creating a hash

You fill a hash from a list of key/value pairs. The fat comma => is a comma that also quotes the word on its left, which makes the pairs easy to read:

PERL
use v5.36;

my %age = (
    alice => 30,
    bob   => 25,
    carl  => 35,
);

my %same = ("alice", 30, "bob", 25);   # a plain comma list works too

A trailing comma after the last pair is allowed and makes editing easier. If a key has spaces or dashes, quote it: "first name" => "Ada". Inside the curly braces of a lookup, a simple word needs no quotes ($age{alice}), but an expression does ($age{$name}, $age{"a b"}).

A hash is a set of labelled boxes

Key A unique string label.
Value Any scalar.
Lookup $h{key} is fast.

Order is not guaranteed.

1 / 2

Reading, adding and changing

Use $hash{key} to read a value, and assign to it to add a new pair or replace an existing one. Reading a key that does not exist returns undef and does not create it:

PERL
say $age{alice};     # 30
$age{dave} = 41;     # adds a pair
$age{bob}++;         # 26, works like any scalar variable

Because a missing key reads as undef, you can tell "missing" from "present" using exists, and "present with a real value" using defined:

PERL
say exists $age{alice} ? "yes" : "no";   # yes
say exists $age{zed}   ? "yes" : "no";   # no
say defined $age{zed}  ? "defined" : "undef";   # undef

The difference matters when a value can legitimately be undef or 0: exists only asks about the key.

To remove a pair, use delete, which returns the removed value:

PERL
my $gone = delete $age{dave};    # 41
say scalar(keys %age);           # 3

keys, values and each

keys %hash returns all the keys, values %hash returns all the values, and in scalar context keys gives the number of pairs. Because the order of a hash is not guaranteed, sort the keys whenever the output order matters:

PERL
say scalar(keys %age);                   # 3
for my $name (sort keys %age) {
    say "$name is $age{$name}";
}
# alice is 30
# bob is 26
# carl is 35

say join " ", sort { $a <=> $b } values %age;   # 26 30 35

Perl deliberately randomizes the key order from one run of the program to the next, so never rely on it. The order is consistent within a single run (keys and values line up with each other), but it will not be alphabetical and it will not be insertion order.

each walks the pairs one at a time. It is handy for big hashes you do not want to copy into a list:

PERL
while (my ($name, $years) = each %age) {
    say "$name: $years";
}

Do not add or delete keys while looping with each. Changing the value of the current key is fine.

Python Creating and querying a hash (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Hash slices

Like arrays, hashes have slices. A slice uses the @ sigil because it returns a list, and the braces hold a list of keys:

PERL
my @pair = @age{qw(alice carl)};          # (30, 35)

my %sub;
@sub{qw(a b c)} = (1, 2, 3);               # sets a=>1, b=>2, c=>3

my %picked = %age{'alice', 'bob'};         # key/value slice: a smaller hash
delete @age{qw(alice bob)};                # delete several keys at once

The %hash{...} form (Perl 5.20 and later) returns keys together with values, so it produces a new hash. @hash{...} returns only the values. Slices make it easy to initialize a hash from two lists:

PERL
my @arr = (1, 2, 3);
my %idx;
@idx{@arr} = (0 .. $#arr);                 # 1=>0, 2=>1, 3=>2

Counting words

The most famous hash job is counting. Missing keys read as undef, and ++ on undef starts from zero without a warning, so the whole counting loop is one statement:

PERL
my %count;
$count{$_}++ for qw(the cat the dog the end);

say join ", ", map { "$_:$count{$_}" } sort keys %count;
# cat:1, dog:1, end:1, the:3

The same pattern collects totals: $total{$category} += $amount; creates each entry the first time it is touched. We build several variations of this in Hash Patterns.

Python Counting and slices (Python stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A hash in list context

When you use a hash where a list is expected, it flattens into key/value pairs, in the same unpredictable order. That has useful consequences:

PERL
my %sub = (a => 1, b => 2, c => 3);

my @flat = %sub;                     # 6 elements: keys and values interleaved
my %copy = (%age, eve => 22);        # copy a hash and add a pair
my %merged = (%sub, a => 100);       # later pairs win: a is now 100
my %inverse = reverse %sub;          # swap keys and values: 1=>"a", 2=>"b", ...

Copying with (%a, %b) is the idiomatic way to merge two hashes, and the later hash overrides duplicate keys. reverse %hash only works well when the values are unique, because duplicate values would collapse into one key.

In a boolean test, an empty hash is false and a non-empty one is true, so say "has data" if %age; works. Modern Perl also returns the number of keys if you call scalar(%age).

Two last details. Interpolating a hash value into a string works for simple keys, "Name: $age{alice}", and with a variable key, "Age of $key is $age{$key}". But a whole hash does not interpolate: "%age" is just the text %age. And if you give the same key twice in a list, the last one wins.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which test tells you whether the key zed is present in %age, even if its value is undef?

    exists asks only about the key. defined and a plain boolean test examine the value, which could be undef or 0 even though the key is present.
  2. 2. Why should you write for my $k (sort keys %h) when output order matters?

    Perl randomizes hash order between runs, so only an explicit sort gives repeatable output.
  3. 3. After my %c; $c{$_}++ for qw(a b a);, what is $c{a}?

    The first ++ starts from undef (treated as 0) without a warning, so a is counted twice.
  4. 4. What does my %inv = reverse %h; do?

    The hash flattens to a list of key/value pairs, reverse flips that list, and the result is read back as value/key pairs.
  5. 5. Which line copies %a and adds one pair without changing %a?

    A hash in list context flattens into pairs, so listing it first and adding more pairs builds a new, larger hash.

Summary

  • A hash maps string keys to scalar values; use %h for the whole hash and $h{key} for one value.
  • exists tests for a key, delete removes a pair, and keys/values list the contents.
  • Key order is not guaranteed, so sort keys %h for stable output.
  • Slices (@h{...}, %h{...}) work on several keys at once, and $h{$_}++ makes a one-line counter.
  • In list context a hash flattens to pairs, which gives copying, merging and reverse for free.

Next: Hash Patterns