TExcelTAD
Home › Perl › Perl Hashes

Perl Hashes

A hash stores key/value pairs: look up a value by its key, as in a dictionary or phone book. Hash variables start with %. Keys are strings; values are any scalars.

perl · try it yourself
use strict;
use warnings;

my %capital = (
    France  => "Paris",
    Japan   => "Tokyo",
    Kenya   => "Nairobi",
);

print "Capital of Japan: $capital{Japan}\n";

$capital{Peru} = "Lima";        # add a pair
$capital{France} = "Paris";     # overwrite (same value here)

print "Countries: ", scalar(keys %capital), "\n";
Capital of Japan: Tokyo
Countries: 4

The fat comma => works like a comma but quotes the word on its left, so you can write France => "Paris" instead of "France", "Paris". A single value is a scalar, so you access it with $ and curly braces: $capital{Japan}.

Hash order is random

A hash has no order. Perl even randomises the order on purpose for security, so it can change from one run to the next. When you need a stable order, sort the keys:

perl · try it yourself
use strict;
use warnings;

my %price = (tea => 3.5, coffee => 4, juice => 5.25, water => 1);

foreach my $item (sort keys %price) {
    printf "%-7s %5.2f\n", $item, $price{$item};
}

print "Cheapest first: ";
print join(", ", sort { $price{$a} <=> $price{$b} } keys %price), "\n";
coffee   4.00
juice    5.25
tea      3.50
water    1.00
Cheapest first: water, tea, coffee, juice

Tip: Never rely on the order of keys, values or each. Always sort when the output order matters.

exists, delete and defined

perl · try it yourself
use strict;
use warnings;

my %login = (alice => "2024-05-01", bob => undef);

for my $user (qw(alice bob carol)) {
    my $state = !exists $login{$user}  ? "unknown user"
              : !defined $login{$user} ? "never logged in"
              :                          "last login $login{$user}";
    print "$user: $state\n";
}

delete $login{bob};
print "After delete: ", join(", ", sort keys %login), "\n";
alice: last login 2024-05-01
bob: never logged in
carol: unknown user
After delete: alice

exists asks "is this key present?", while defined asks "is the value not undef?". delete removes the pair entirely.

Iterating

keys returns all keys, values all values, and each returns one key/value pair at a time:

perl · try it yourself
use strict;
use warnings;

my %inventory = (bolts => 120, nuts => 75, screws => 300);

my $total = 0;
$total += $_ for values %inventory;
print "Total parts: $total\n";

for my $part (sort keys %inventory) {
    print "$part => $inventory{$part}\n";
}
Total parts: 495
bolts => 120
nuts => 75
screws => 300

Counting with a hash

The single most common hash idiom is counting how often something occurs. A missing key reads as undef, and ++ on undef gives 1, so no setup is needed:

perl · try it yourself
use strict;
use warnings;

my @votes = qw(red blue red green blue red);
my %count;
$count{$_}++ for @votes;

for my $color (sort { $count{$b} <=> $count{$a} || $a cmp $b } keys %count) {
    print "$color: $count{$color}\n";
}

my %seen;
my @unique = grep { !$seen{$_}++ } @votes;
print "Unique in order: @unique\n";
red: 3
blue: 2
green: 1
Unique in order: red blue green

The grep { !$seen{$_}++ } line is a famous idiom: the first time a value is seen, $seen{$_} is 0 (false), so ! makes it true and the value is kept; afterwards it is positive and the value is dropped.

Hash slices and conversion

perl · try it yourself
use strict;
use warnings;

my %user = (name => "Kim", age => 34, city => "Seoul", role => "dev");

my @info = @user{qw(name city)};          # hash slice: list of values
print "Info: @info\n";

my %subset = %user{qw(name role)};        # key/value slice
print join(", ", map { "$_=$subset{$_}" } sort keys %subset), "\n";

my %by_value = reverse %user;             # swap keys and values
print "Who is 34? $by_value{34}\n";
Info: Kim Seoul
name=Kim, role=dev
Who is 34? age

reverse on a hash turns values into keys; it only works well when the values are unique.

Test yourself

How do you read the value for key apple from %stock?

  1. %stock{apple}
  2. $stock[apple]
  3. $stock{apple}
  4. @stock{apple}

What is the difference between exists $h{k} and defined $h{k}?

  1. None
  2. exists checks the key is present; defined checks the value is not undef
  3. defined deletes the key
  4. exists only works on arrays

Why do examples use sort keys %h when printing?

  1. keys only works with sort
  2. Hash order is unpredictable, so sorting gives a stable order
  3. It is faster
  4. It removes duplicate keys