Perl Scripts ·

Perl Hashes: Add Values, Count Keys and Loop Safely

By Manu Mathew, Technical Lead Engineer · Published 28 January 2016 · Last updated 5 October 2026

Isometric illustration of key tags linked to small boxes, with one key and box pair in blue

Hashes hold most of the interesting data in a Perl program: configuration, records from a database, lookups. This page started as a note on looping over a Perl hash safely, and now also covers the shorter hash notes I wrote between 2014 and 2016.

Quick answer

Add an entry with $hash{$key} = $value, or pair two arrays with a slice, @hash{@keys} = @values. scalar(keys %hash) counts the entries. Loop with keys when you need the keys or may change the hash, values for values only, and each only for simple read-only loops.

I tested each example with Perl 5.40, using use strict and use warnings.

How do I add values to a hash?

Assign to $hash{$key}; to pair up two arrays, assign one to a hash slice keyed by the other.

use strict;
use warnings;

my %stock;
$stock{tea}    = 20;           # add or overwrite one entry
$stock{coffee} = 35;

# Pair up two arrays in one step with a hash slice
my @ids   = (1, 2, 3);
my @names = ('Asha', 'Ravi', 'Joe');
my %name_for;
@name_for{@ids} = @names;

print "$name_for{2}\n";        # Ravi

The slice replaces a loop over indexes. If the arrays differ in length, extra keys get undef and extra values are ignored.

How do I count the entries in a hash?

keys in scalar context returns the number of entries, and a hash in boolean context is true when it isn’t empty.

use strict;
use warnings;

my %team = (a => 'Max', b => 'Rac', c => 'Neo');
my $size = keys %team;         # keys in scalar context counts the entries
print "$size\n";               # 3
print scalar(keys %team), "\n";# 3
print "The hash is not empty\n" if %team;

How do I loop over keys, values, or both?

use strict;
use warnings;

my %stock = (apples => 3, pears => 0, plums => 7);

# Keys only (sorted, so the order is predictable)
for my $fruit (sort keys %stock) {
    print "$fruit\n";
}

# Values only
my $total = 0;
$total += $_ for values %stock;
print "Total: $total\n";

# Keys and values together
for my $fruit (sort keys %stock) {
    print "$fruit: $stock{$fruit}\n";
}

Hash order in Perl is deliberately unpredictable and can change between runs, so sort the keys whenever the output order matters.

Can I change the hash while looping?

Yes, if you loop over keys: the list of keys is built before the loop starts, so adding entries doesn’t disturb it.

for my $fruit (keys %stock) {
    $stock{ uc $fruit } = $stock{$fruit} * 2;    # adds new keys safely
}

When is each() safe?

each walks the hash with an internal iterator. Adding or deleting entries during the loop has unspecified results, with one exception: deleting the key that each just returned is safe. Reset the iterator with keys %hash before the loop, in case an earlier loop stopped part-way.

keys %stock;    # reset the iterator
while (my ($fruit, $count) = each %stock) {
    delete $stock{$fruit} if $count == 0;    # deleting the current key is safe
}

How do I visit every value in nested hashes and arrays?

Write a small recursive function that checks ref and handles hashes, arrays and plain values separately.

use strict;
use warnings;

# Visit every plain value in a nested structure of hashes and arrays
sub walk {
    my ($node, $visit) = @_;
    if (ref $node eq 'HASH') {
        $node->{$_} = walk($node->{$_}, $visit) for sort keys %$node;
    }
    elsif (ref $node eq 'ARRAY') {
        $_ = walk($_, $visit) for @$node;
    }
    else {
        $node = $visit->($node);
    }
    return $node;
}

my %config = (
    site  => { name => 'shop', tags => ['perl', 'cgi'] },
    ports => [80, 443],
);
walk(\%config, sub { defined $_[0] ? "--$_[0]--" : $_[0] });

print "$config{site}{name} $config{site}{tags}[1] $config{ports}[0]\n";
# --shop-- --cgi-- --80--

The older version of this note did the same with separate is_hash and is_array helpers and an eval. ref $node eq 'HASH' and eq 'ARRAY' are enough for plain data. For JSON-like data, the callback is a convenient place to trim strings or mask values before logging.

Frequently asked questions

Why does my hash come out in a different order each time?

Perl deliberately randomises hash order, and it can change between runs. If you need a stable order, sort the keys: for my $k (sort keys %h). To keep the order you added them in, also store the keys in an array, or use Tie::IxHash from CPAN.

How do I check whether a key exists?

Use exists $hash{$key}. It is true even when the value is undef or 0, unlike if ($hash{$key}), which is false for those values. In nested data, test each level in turn, because checking a deep key can create the levels above it.

How do I delete a key from a hash?

delete $hash{$key} removes the key and its value and returns the value. You can delete several keys at once with a slice: delete @hash{qw(a b)}. Inside an each loop, deleting the key you have just been given is safe.

How do I merge two hashes?

Assign both into a new hash: my %all = (%defaults, %options);. When a key appears in both, the value from the later hash wins, which makes this a simple way to apply user options over a set of defaults.

Related notes: Perl arrays: length, add, remove and search; multidimensional arrays in Perl; sorting arrays in Perl; hiring a remote Perl developer.

Need help with Perl code?

If you have Perl code that needs fixing, extending or upgrading, I’m happy to take a look. I work remotely from Kozhikode, Kerala, with teams across India and elsewhere; Perl development and maintenance explains how I help. If you are deciding how to bring someone in, Hiring a remote Perl developer is a short checklist.

You can reach me through the contact section or email me at manu@manu.co.in. A few lines about the system and what you need is a good start.

An earlier version of the looping sections reproduced a Stack Overflow answer (answer 3360, CC BY-SA). This version is rewritten in my own words, with new examples.

Sources: perldata: hashes and slices; perlfunc: keys; perlfunc: each; perlfunc: ref; Stack Overflow question 3033.

Back to the blog